import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, ViewController } from 'ionic-angular';

// native
import { Geolocation } from '@ionic-native/geolocation';
import { LoadingService } from '../../../providers/utils/loading.service';
import { AlertService } from '../../../providers/utils/alert.service';
import {removeAddressEmpty} from "../../../utils/basic";

/** 百度地图定位
 */
declare let BMap;
@IonicPage()
@Component({
  selector: 'page-load-map',
  templateUrl: 'load-map.html',
})
export class LoadMapPage {

  // 百度地图
  private map: any;
  // 地址
  private address: string= '地理位置';

  @ViewChild('map') mapElement: ElementRef;
  constructor(
    private geolocation: Geolocation,
    public viewCtrl: ViewController,
    private loadingCtrl: LoadingService,
    private alertCtrl: AlertService,
  ) {
  }

  ionViewDidLoad() {
  }

  // ionViewDidEnter() {
  ionViewWillEnter() {
    this.loadingCtrl.createLoading('正在获取中');
      this.geolocation.getCurrentPosition()
        .then(resp => {
          debugger;
        let x = resp.coords.longitude,
          y = resp.coords.latitude;
        this.createBDMap(x,y);
      }).catch(error => {
        this.loadingCtrl.closeLoading().then(()=>{
          this.alertCtrl.createMessageAlert('提示','获取地图信息失败,请确定是否打开精确定位?');
          console.log('Error getting location', error);
        });
      });
    // this.createBDMap(121.417711,31.188859);
      /*navigator.geolocation.getCurrentPosition(resp=>{
        debugger;
        try {
          let x = resp.coords.longitude,
            y = resp.coords.latitude;
          this.createBDMap(x,y);
        }catch (err) {
          console.log(err);
          this.loadingCtrl.closeLoading();
        }

      });*/
      // 去除百度定位
      /*const geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition((r) => {
        debugger;
        if (!r) this.createBDMap(121.48789949, 31.24916171);
        debugger;
        this.baiduLoaction(r.point.lng, r.point.lat);
        const addComp = r.address;
        // const { city, district, street,street_number }= addComp;
        const address = `${addComp.city},${addComp.district},${addComp.street}${addComp.street_number}`;
        const arr= address.split(',');
        const newArr= arr.filter(value => value);
        this.address= newArr.join(',');

        this.loadingCtrl.closeLoading();
        this.ref.detectChanges();
      }, {enableHighAccuracy: true})*/
  }
  // 百度地图
  private baiduLoaction(x,y)
  {
    this.map = new BMap.Map(this.mapElement.nativeElement, {enableMapClick: true});//创建地图实例
    var point = new BMap.Point(x,y);
    this.map.centerAndZoom(point,16);
    this.handleClick();

    this.openControl();
  }

  /*** 初始化地图
   * @param x 经度
   * @param y 纬度
   * */
  createBDMap(x, y) {
    this.map = new BMap.Map(this.mapElement.nativeElement, {enableMapClick: true});//创建地图实例
    this.map.enableScrollWheelZoom();//启动滚轮放大缩小，默认禁用
    this.map.enableContinuousZoom();//连续缩放效果，默认禁用

    let point = new BMap.Point(x, y);//坐标可以通过百度地图坐标拾取器获取
    this.map.centerAndZoom(point, 16);//设置中心和地图显示级别

    //坐标转换完之后的回调函数
    const translateCallback= data=> {
      if(data.status === 0) {
        let marker = new BMap.Marker(data.points[0]);
        this.map.addOverlay(marker);

        const point= data.points[0];
        this.map.setCenter(point);
        this.getAddress(point);
      }
    };

    let convertor = new BMap.Convertor();
    convertor.translate([point], 1, 5, translateCallback);

    this.map.addEventListener("tilesloaded",()=> {
      // alert("地图加载完毕");
    });
    this.loadingCtrl.closeLoading();
    this.handleClick();

    this.openControl();
  }
  /*** 反向解析地址
  * */
  handleClick(){
    const showInfo = (e)=> {
      const pt = e.point;
      this.getAddress(pt);
    };
    this.map.addEventListener("click", showInfo);
  }

  /*** 反向解析地址
   * @param point 百度坐标
   * */
  getAddress(point){
    const geocode = new BMap.Geocoder();
    geocode.getLocation(point, (rs)=> {
      this.address = removeAddressEmpty(rs.addressComponents);
    });
  }

  /*** 打开控制台
  * */
  openControl(){
    // 添加带有定位的导航控件
    let navigationControl = new BMap.NavigationControl({
      // 靠左上角位置
      anchor: 'BMAP_ANCHOR_TOP_LEFT',
      // LARGE类型
      type: 'BMAP_NAVIGATION_CONTROL_LARGE',
      // 启用显示定位
      enableGeolocation: true
    });
    this.map.addControl(navigationControl);

    // 添加定位控件
    let geolocationControl = new BMap.GeolocationControl();
    geolocationControl.addEventListener("locationSuccess", e=> {
      // 定位成功事件
      this.address = removeAddressEmpty(e.addressComponent);
    });
    geolocationControl.addEventListener("locationError", e=> {
      // 定位失败事件
      alert(e.message);
    });
    this.map.addControl(geolocationControl);
  }


  /*** 确定选择
   * */
  executeConfirm(e){
    e.stopPropagation();
    if(this.address==='地理位置' || !this.address) return;
    this.viewCtrl.dismiss(this.address);
  }

}
